package com.xiaouyudeguang.common.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.xiaouyudeguang.common.utils.JsonObject;
import com.xiaouyudeguang.common.utils.RestTemplateUtils;

public class WeChatClient {

    /**
     * 移动应用登录(https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Authorized_API_call_UnionID.html)
     * @param appKey
     * @param secret
     * @param code
     * @return
     * @throws Exception
     */
    public static JsonNode loginByCode(String appKey, String secret, String code) throws Exception {
        String API_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={1}&secret={2}&code={3}&grant_type=authorization_code";
        String result = RestTemplateUtils.getForObject(API_URL, String.class, appKey, secret, code);
        return JsonObject.readTree(result);
    }

    /**
     * 根据openid获取用户信息
     * @param accessToken
     * @param openid
     * @return
     * @throws Exception
     */
    public static JsonNode userinfo(String accessToken, String openid) throws Exception {
        String API_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={1}&openid={2}";
        String result = RestTemplateUtils.getForObject(API_URL, String.class, accessToken, openid);
        return JsonObject.readTree(result);
    }

}
